package com.example.person_web.core.service.impl;

import com.example.person_web.common.DateUtil;
import com.example.person_web.common.RandomNumber;
import com.example.person_web.common.WrapperResponse;
import com.example.person_web.core.component.JwtUtil;
import com.example.person_web.core.dao.LoginRegisterDAO;
import com.example.person_web.core.dto.UserInfoDTO;
import com.example.person_web.core.entity.UserContext;
import com.example.person_web.core.entity.UserInfoDO;
import com.example.person_web.core.service.LoginRegisterService;
import com.google.code.kaptcha.Producer;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

@Service
public class LoginRegisterServiceImpl implements LoginRegisterService {
    @Autowired
    private LoginRegisterDAO loginRegisterDAO;
    @Autowired
    private Producer kaptchaProducer;
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 登录接口
     *
     * @param userInfoDTO
     * @return
     */
    @Override
    public WrapperResponse login(UserInfoDTO userInfoDTO) {
        if (userInfoDTO.getAccount() == null || userInfoDTO.getAccount().isEmpty()) {
            return WrapperResponse.fail("账号不可以为空", null);
        }
        if (userInfoDTO.getPassword() == null || userInfoDTO.getPassword().isEmpty()) {
            return WrapperResponse.fail("密码不可以为空", null);
        }
        UserInfoDO account = loginRegisterDAO.queryUserInfoByAccount(userInfoDTO.getAccount());
        if (account == null) {
            return WrapperResponse.fail("该账号不存在", null);
        }
        UserInfoDO userInfoDO = loginRegisterDAO.queryUserInfoByAccountAndPassword(userInfoDTO.getAccount(), userInfoDTO.getPassword());
        if (userInfoDO == null) {
            return WrapperResponse.fail("密码错误", null);
        }
        return WrapperResponse.success(userInfoDO);
    }

    /**
     * 注册接口
     *
     * @param userInfoDTO
     * @return
     */
    @Override
    public WrapperResponse register(UserInfoDTO userInfoDTO) {
        if (userInfoDTO.getAccount() == null || userInfoDTO.getAccount().isEmpty()) {
            return WrapperResponse.fail("账号不可以为空", null);
        }
        if (userInfoDTO.getPassword() == null || userInfoDTO.getPassword().isEmpty()) {
            return WrapperResponse.fail("密码不可以为空", null);
        }
        UserInfoDO userInfoDO = new UserInfoDO();
        userInfoDO.setUserId(DateUtil.getCurrentDateStr() + RandomNumber.getFourRandomNumber());
        userInfoDO.setAccount(userInfoDTO.getAccount());
        userInfoDO.setPassword(userInfoDTO.getPassword());
        userInfoDO.setNickName(userInfoDTO.getNickName());
        userInfoDO.setCreateTime(DateUtil.getCurrentDate());
        userInfoDO.setUpdateTime(DateUtil.getCurrentDate());
        userInfoDO.setLastDay(DateUtil.getCurrentDate());
        userInfoDO.setAvatar("null");
        userInfoDO.setValiFlag("1");
        userInfoDO.setUseDays(0);
        userInfoDO.setBackground(null);
        int insertResult = loginRegisterDAO.insertUserInfo(userInfoDO);
        if (insertResult == 0) {
            return WrapperResponse.fail("注册失败", null);
        }
        return WrapperResponse.success("注册成功", null);
    }

    /**
     * 获取验证码接口
     *
     * @param userInfoDTO
     * @return
     */
    @Override
    public WrapperResponse queryCode(UserInfoDTO userInfoDTO) throws IOException {
        if (userInfoDTO.getAccount() == null || userInfoDTO.getAccount().isEmpty()) {
            return WrapperResponse.fail("账号不可以为空！", null);
        }
        //判断是不是注册
        if (userInfoDTO.getLoginFalg().equals("0")) {
            UserInfoDO userInfoDO = loginRegisterDAO.queryUserInfoByAccount(userInfoDTO.getAccount());
            if (userInfoDO != null) {
                return WrapperResponse.fail("该账号已重复", null);
            }
        }
        // 生成验证码文本
        String captchaText = kaptchaProducer.createText();
        //TODO 将验证码存储到redis中

        // 生成验证码图片
        BufferedImage captchaImage = kaptchaProducer.createImage(captchaText);
        // 将图片转换为Base64编码
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(captchaImage, "JPEG", baos);
        byte[] imageBytes = baos.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        return WrapperResponse.success("成功", base64Image);
    }

    @Override
    public WrapperResponse autoLogIn(HttpServletRequest request) {
        String authorizationHeader = request.getHeader("Authorization");
        String username = null;
        String jwt = null;
        // 从请求头中提取JWT
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }

        // 如果用户名存在且尚未认证，则进行认证
        if (username != null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            // 验证JWT
            if (jwtUtil.validateToken(jwt, userDetails)) {
                UserInfoDO userInfoDO = loginRegisterDAO.queryUserInfoByAccount(username);
                return WrapperResponse.success(userInfoDO);
            } else {
                return WrapperResponse.fail("jwt验证失败");
            }
        }
        return WrapperResponse.fail("jwt中的用户名不存在");
    }

    @Override
    public WrapperResponse setBackground(String imageUrl,HttpServletRequest request) {
        String authorizationHeader = request.getHeader("Authorization");
        String username = null;
        String jwt = null;
        // 从请求头中提取JWT
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }
        UserInfoDO userInfoDO = new UserInfoDO();
        userInfoDO.setAccount(username);
        userInfoDO.setBackground(imageUrl);
        int result = loginRegisterDAO.updateBackground(userInfoDO);
        if(result!=0){
            return WrapperResponse.success(imageUrl);
        } else {
            return WrapperResponse.fail("失败");
        }
    }
}
